<template>
    <div class="portList">
        <Card :bordered="false" dis-hover class="ivu-mt">
            <Row :gutter="12">
                <Col span="5">
                    <Tree children-key="project_names_arr" ref="tree" :data="treeList" @on-select-change="treeChange"></Tree>
                </Col>
                <Col span="19">
                    <div class="treated">
                        <span>{{ treatedProject }}</span> 已治疗（<span>{{ treated }}</span>）
                    </div>
<!--                    <table-form :rooms="roomList" :projects="projectList" ref="searchForm" @search="onSearch"/>-->
                    <table-form ref="searchForm" @search="onSearch" :rooms="roomList" @editText="editText"/>
                    <div class="i-table-no-border">
                        <Table border size="small" ref="table" :columns="columns" :data="data" :loading="loading">
                            <template slot-scope="{ row }" slot="hospital">
                                <span>{{row.name}}</span>
                                <Tag class="blueStatus ivu-ml-16" v-if="+row.in_hospital_status===1" color="primary">{{ `${+row.in_hospital_status === 1 ? '住院' : ''}` }}</Tag>
                            </template>
                            <template slot-scope="{ row, index }" slot="action">
                                <a @click="handleDetail(row)">详细</a>
                                <Divider type="vertical"/>
                                <a v-if="editStatus(row)&&row.modify" @click="handleEdit(row)">修改</a>
                                <a v-else class="colorGray">修改</a>
                            </template>
                        </Table>
                        <div class="ivu-mt ivu-text-center">
                            <Page
                                :total="total"
                                :current.sync="page"
                                show-total
                                show-elevator
                                :page-size="pageSize"
                                @on-change="changePage"
                                :page-size-opts="pageOpts"
                                show-sizer transfer
                                @on-page-size-change="changePageSize"
                            />
                        </div>
                    </div>
                </Col>
            </Row>
        </Card>
        <Modal :z-index="0" v-model="inputTreatment" draggable :mask-closable= "false" footer-hide width="600" :title="treatmentText">
            <div class="numTerment">
                <Input @keydown.enter.native.prevent="searchTeatmentList" v-model="formItem.clinic_number" placeholder="请输入患者姓名/诊疗号" :clearable="false"></Input>
            </div>
            <div class="footerClinic">
                <div class="clinicItem" v-for="(item, index) in footerClinic" :key="'item' + index">
                    <Card dis-hover>
                        <div slot="title"><strong class="h-3">{{ item.name }}</strong>
                            <span class="ivu-ml-16">{{item.gender + ' '}}{{item.age}}</span>
                            <span class="ivu-ml-16">诊疗号：{{ item.patient_card_id }}</span>
                            <span class="ivu-ml-16" v-show="item.assess_name"><tag color="primary">{{ item.assess_name }}</tag></span>
                        </div>
                        <div slot="extra">
                            <span class="surplus">正常剩余：<b class="success">{{ item.total_num }}</b></span>
                            <span class="surplus">援助剩余：<b class="warning">{{ item.help_num }}</b></span>
                        </div>
                        <Row :gutter="12">
                            <i-Col span="16" class="footer-line">
                                <p>上次治疗时间：{{ item.recently_clinic_time }} </p>
                                <p>上次治疗数量：{{ item.recently_clinic_num + item.recently_surplus_num }} 个</p>
                            </i-Col>
                            <i-Col span="8" class="ivu-text-righte">
                                <Button type="primary" @click="handleAddTreatment(item, index)" size="large">开始治疗</Button>
                            </i-Col>
                        </Row>
                    </Card>
                </div>
            </div>
        </Modal>
        <template-fore @putMessage="putMessage" @edit="editList" ref="TemplateFore" :isEdit="isEdit"></template-fore>
        <table-drawer :projects="projectList" ref="tableDraw" />
    </div>
</template>
<script>
    import tableForm from './table-form';
    import tableDrawer from './table-drawer';
    import TemplateFore from './templateFore';
    import { formatWithYear } from '@/utils/datetime';
    import { GetTreatmentList, GetTreatmentTree, GetTreatmentInput, clinictreatmentmanagecliniclist } from '@api/treatment';
    import mixins from '@/utils/mixins'
    export default {
        name: 'medical',
        components: { tableForm, tableDrawer, TemplateFore },
        mixins: [mixins],
        data () {
            return {
                inputTreatment: false,
                isEdit: '',
                treatmentText: '',
                treatedProject: '',
                treated: 0,
                template: '',
                formItem: {
                    clinic_number: ''
                },
                loading: false,
                drawer: false,
                pageSize: 10,
                pageOpts: [10, 20, 30, 50],
                columns: [
                    {
                        title: '基本信息',
                        // key: 'name',
                        slot: 'hospital',
                        minWidth: 130
                    },
                    {
                        title: '诊疗号',
                        key: 'patient_card_id',
                        minWidth: 118
                    },
                    {
                        title: '诊室',
                        key: 'clinic_name',
                        minWidth: 118
                    },
                    {
                        title: '治疗时间',
                        key: 'recently_clinic_time',
                        sortable: true,
                        minWidth: 117
                    },
                    {
                        title: '治疗数量',
                        key: 'num',
                        minWidth: 119
                    },
                    {
                        title: '操作人',
                        key: 'operate_name',
                        minWidth: 118
                    },
                    {
                        title: '操作',
                        minWidth: 118,
                        slot: 'action'
                    }
                ],
                data: [],
                roomList: [],
                projectList: [],
                searchForm: {
                    time: this.formDate(new Date()),
                    keywords: '',
                    clinic_project_id: '', // 治疗项目
                    treatment_room_id: '', // 治疗室
                    clinic_ids: ''
                },
                modal: false,
                treeList: [],
                footerClinic: [],
                oldId: '',
                listIndex: ''
            }
        },
        created () {
            this.getTree()
            clinictreatmentmanagecliniclist().then(res => {
                this.roomList = res
            })
        },
        methods: {
            getTree () {
                GetTreatmentTree().then(res => {
                    let status = true
                    for (let i = 0; i < res.length; i++) {
                        if (res[i].expand) {
                            if (status) {
                                this.searchForm.treatment_room_id = res[i].id
                                this.treatmentText += res[i].title + '-'
                            }
                        }
                        if (res[i].project_names_arr && res[i].project_names_arr.length !== 0) {
                            for (let j = 0; j < res[i].project_names_arr.length; j++) {
                                res[i].project_names_arr[j].inx = i + '-' + j
                                if (status && res[i].project_names_arr[j].title.indexOf('308') !== -1) {
                                    res[i].project_names_arr[j].selected = true
                                    this.treatedProject = res[i].project_names_arr[j].title
                                    this.treatmentText += res[i].project_names_arr[j].title
                                    this.searchForm.clinic_project_id = res[i].project_names_arr[j].id
                                    this.template = res[i].project_names_arr[j].template
                                    status = false
                                }
                            }
                        }
                    }
                    this.treeList = res
                    this.onLoad()
                })
            },
            editList (id, temp) {
                this.$refs.tableDraw.handleDetail({ id: this.oldId, patient_card_id: id, clinic_project_id: this.searchForm.clinic_project_id }, 1, temp)
            },
            onLoad () {
                this.loading = true
                const params = this.getParam()
                GetTreatmentList(params).then((res) => {
                    this.treated = res.total || 0
                    this.data = res.list
                    this.total = res.total
                }).finally(() => {
                    this.loading = false
                })
            },
            getParam () {
                let param = {
                    page: this.page,
                    pageSize: this.pageSize
                }
                param = Object.assign(param, this.searchForm)
                return param
            },
            fliteItem (arr) {
                let reArr = [];
                if (arr && arr.length > 0) {
                    arr.forEach((item) => {
                        const reItem = item;
                        let genderStr = '不详';
                        if (item.gender === '1') genderStr = '男'
                        else if (item.gender === '2') genderStr = '女'
                        item.basic = item.name + ' ' + genderStr + ' ' + item.age + '岁';
                        reArr.push(reItem);
                    })
                }
                return reArr;
            },
            // 显示详情
            handleDetail (row) {
                this.oldId = row.id
                this.$refs.tableDraw.handleDetail(row, false, this.template)
            },
            getConfigId () {
                return {
                    clinic_project_id: this.searchForm.clinic_project_id,
                    treatment_room_id: this.searchForm.treatment_room_id
                }
            },
            // 表格内容编辑
            handleEdit (row) {
                this.isEdit = row.operate_name
                this.oldId = row.id
                this.$refs.TemplateFore.templateList(row, this.template, this.treatedProject, 1, this.getConfigId(), 2, null)
            },
            changePage (page) {
                this.page = page;
                this.onLoad();
            },
            changePageSize (pagesize) {
                this.pageSize = pagesize;
                this.onLoad();
            },
            onSearch (data) {
                this.searchForm.time = data.date !== '' ? this.formDate(data.date) : ''
                this.searchForm.keywords = data.name
                this.searchForm.clinic_ids = data.room.join(',')
                this.onLoad();
            },
            // 模糊搜索诊疗号
            searchTeatmentList (e) {
                if (this.formItem.clinic_number === '') {
                    this.$Message.error('诊疗号不能为空')
                    return false
                }
                const config = {
                    clinic_project_id: this.searchForm.clinic_project_id,
                    keywords: this.formItem.clinic_number
                }
                GetTreatmentInput(config).then(res => {
                    this.footerClinic = res
                    if (res.length === 0) {
                        this.$Message.warning('当前搜索无数据')
                    }
                })
            },
            formDate (date) {
                return formatWithYear(date, '-')
            },
            closeEdit (val) {
                if (val) {
                    this.onLoad();
                }
            },
            // 点击树获取对应数据
            treeChange (node, item, e, i) {
                this.formItem.clinic_number = ''
                this.footerClinic = []
                const inx = item.inx
                if (node.length > 0) {
                    // 点击树
                    this.$refs.searchForm.treeChangeTime()
                    this.template = item.template
                    this.treatedProject = item.title
                    const name = this.getParent(item.id, inx)
                    this.treatmentText = name.title + '-' + item.title
                    this.searchForm.clinic_project_id = item.id
                    this.searchForm.treatment_room_id = name.id
                    this.searchForm.time = this.formDate(new Date())
                    this.onLoad()
                } else {
                    // 点击取消树
                    this.treatedProject = ''
                    this.treatmentText = ''
                    this.searchForm.clinic_project_id = ''
                    this.searchForm.treatment_room_id = ''
                    this.treated = 0
                    this.data = []
                }
            },
            getParent (id, inx) {
                let parent = null
                const data = this.treeList
                for (let i = 0; i < data.length; i++) {
                    if (data[i].project_names_arr && data[i].project_names_arr.length > 0) {
                        for (let j = 0; j < data[i].project_names_arr.length; j++) {
                            if (data[i].project_names_arr[j].id === id && data[i].project_names_arr[j].inx === inx) {
                                parent = data[i]
                                return parent
                            }
                        }
                    }
                }
                return parent
            },
            editText () {
                if (this.searchForm.clinic_project_id === '' || this.searchForm.treatment_room_id === '') {
                    this.$Message.warning('请选择治疗项目')
                    return false
                }
                this.inputTreatment = true
            },
            // 点击治疗 录入  add
            handleAddTreatment (row, index) {
                // debugger
                this.isEdit = ''
                this.listIndex = index
                this.$refs.TemplateFore.templateList(row, this.template, this.treatedProject, 2, this.getConfigId(), 1, null)
                this.inputTreatment = false
            },
            // 判断当前数据能不能修改
            editStatus (row) {
                const timesTamp = 3 * 24 * 60 * 60 * 1000
                const time = row.recently_clinic_time
                const startTime = new Date(time).getTime()
                const endTime = (new Date()).getTime() || (new Date()).valueOf()
                if ((endTime - startTime) > timesTamp) return false
                else return true
            },
            // 录入治疗成功
            putMessage () {
                this.onLoad()
                this.footerClinic.splice(this.listIndex, 1)
                this.formItem.clinic_number = ''
                this.inputTreatment = false
            }
        }
    }
</script>
<style scoped lang="less">
    .treated {
        height: 24px;
        line-height: 24px;
        font-size: 16px;
        font-weight: 700;
        margin: 16px 0;
    }
    .numTerment {
        margin-bottom: 24px;
    }
    .footerClinic {
        max-height: 500px;
        overflow-y: auto;
        /deep/.ivu-card {
            margin-bottom: 12px;
            &:last-child {
                margin-bottom: 0;
            }
        }
        .h-3 {
            font-size: 16px;
            font-weight: 700;
        }
        .surplus {
            color: #777;
            margin-right: 16px;
            b {
                font-size: 16px;
                margin-left: 8px;
            }
        }
        .success {
            color: #19be6b;
        }
        .warning {
            color: #f90;
        }
    }
    .colorGray {
        color: #999 !important;
        cursor: text !important;
    }
    .clinicItem {
        margin-bottom: 12px;
        &:last-child {
            margin-bottom: 0;
        }
    }
</style>
